package com.tian.excel.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tian.excel.entity.Dept;
import com.tian.excel.mapper.DeptDao;
import com.tian.excel.service.DeptService;
import com.tian.excel.vo.DeptVo;
import com.tian.excel.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * @author: Tian
 * @version: 1.0
 * @since: 1.0
 * @date: 2024/7/14/11:44
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptDao deptDao;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    //@Cacheable(cacheNames = "dept")
    public R selectAll(DeptVo deptVo) {
        HashOperations<String, Object, Object> sho = redisTemplate.opsForHash();

        //if(StringUtils.isEmpty(deptVo.getDeptno()))

        //vo.set("dept::"+deptVo.getDeptno(), JSONUtil.toJsonStr(deptVo));


        IPage<Dept> page = new Page<>(deptVo.getCurrent(),deptVo.getSize());
        QueryWrapper<Dept> wrapper=new QueryWrapper();
        if(!StringUtils.isEmpty(deptVo.getDeptno())){
            wrapper.eq("deptno",deptVo.getDeptno());
        }
        if(!StringUtils.isEmpty(deptVo.getDname())){
            wrapper.like("dname",deptVo.getDname());
        }

        List<Dept> depts = deptDao.selectList(page,wrapper);
        if(depts==null){
            return new R(200,"抱歉,找不到你需要的信息",depts);
        }
        page.setRecords(depts);
        return new R(200,"查询成功",page);
    }

    @Override
    public R insertDept(Dept dept) {
        int i = deptDao.insert(dept);
        if(i==0){
            return new R(500,"添加失败",i);
        }
        return new R(200,"添加部门成功",i);

    }

    @Override
    public R updateById(Dept dept) {
        int i = deptDao.updateById(dept);
        if(i==0){
            return new R(500,"修改部门信息失败",i);
        }
        ValueOperations ho = redisTemplate.opsForValue();
        ho.set("dept::"+dept.getDeptno(),dept);
        return new R(200,"修改部门信息成功",i);
    }

    @Override
    public R deleteById(int id) {
        int i = deptDao.deleteById(id);
        if (i==0){
            return new R(404,"该部门不存在",i);
        }
        redisTemplate.delete("dept::"+id);
        return new R(200,"成功删除该部门",i);
    }
}
